// src/service/sseService.js
import { ref } from 'vue';
import { useSSE } from '@/utils/useSSE-web.js';
import { useMessageStore } from '@/store/message-web.js';

export function useSseService() {
  const messageStore = useMessageStore();
  const { eventData, error, isConnected, connect, closeConnection } = useSSE();
  const eventSource = ref(null);
  const baseUrl = 'http://172.172.9.62:8091/service-sse';

  /**
   * 连接SSE服务
   * @param {string} phone - 用户手机号
   * @param {number} identity - 用户身份 (1:乘客)
   */
  const connectSSE = (phone, identity) => {
    error.value = null;
    
    // 关闭已存在的连接
    if (eventSource.value) {
      closeSSE();
    }
    
    eventSource.value = connect(
      `${baseUrl}/connect`,
      { phone, identity },
      (data) => {
        console.log("收到消息:", data);
        
        if (data.trim() === '') return;
        
        if (data.includes('HEARTBEAT')) {
          console.log("心跳检测");
        } else if (data.includes('SSE_CONNECTED')) {
          console.log('SSE连接已建立');
        } else if (data.includes('SSE_CLOSED')) {
          console.log('SSE连接已关闭');
        } else if (data.includes('Keep-alive')) {
          return;
        } else {
          // 处理业务消息
          messageStore.setLatestMessage(data);
          messageStore.addPushedMessage(data);
          console.log('收到推送消息:', data);
        }
      }
    );
  };

  /**
   * 重连SSE服务
   */
  const reconnectSSE = (phone, identity) => {
    if (isConnected.value) {
      console.log('已经建立连接，无需重连');
      return;
    }
    
    console.log('正在尝试重连...');
    connectSSE(phone, identity);
  };

  /**
   * 关闭SSE连接
   */
  const closeSSE = () => {
    if (!eventSource.value) return;
    
    // 调用后端关闭接口
    axios.get(`${baseUrl}/close`, {
      params: { 
        phone: localStorage.getItem('userPhone'),
        identity: localStorage.getItem('userIdentity')
      }
    }).finally(() => {
      closeConnection();
      eventSource.value = null;
      console.log('SSE 连接已关闭');
    });
  };

  return {
    eventData,
    error,
    isConnected,
    connectSSE,
    reconnectSSE,
    closeSSE
  };
}